package part04;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;

import java.util.Properties;

public class SourceFromKafka {
    public static void main(String[] args) throws Exception {
        //1,定义flink stream执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        //2,从kafka主题中获取数据源
        Properties prop = new Properties();
        prop.setProperty("bootstrap.servers", "centos7-1:9092");
        prop.setProperty("group.id", "test");
        FlinkKafkaConsumer<String> consumer = new FlinkKafkaConsumer<>("kafkaFlink", new SimpleStringSchema(), prop);
        consumer.setStartFromEarliest();
        DataStreamSource<String> data = env.addSource(consumer).setParallelism(1);
        //3,处理数据
        SingleOutputStreamOperator<Tuple2<String, Long>> flatMap = data.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
                String[] split = value.split("\\s+");
                for (String word : split) {
                    out.collect(new Tuple2<>(word, 1L));
                }
            }
        }).setParallelism(1);
        SingleOutputStreamOperator<Tuple2<String, Long>> sum = flatMap.keyBy(0).sum(1);
        //输出数据到控制台
        sum.print();
        env.execute();
    }
}
